//
//  WJComposePictureView.swift
//  WJWeiBo
//
//  Created by wangjun on 16/7/28.
//  Copyright © 2016年 wangjun. All rights reserved.
//

import UIKit
// cell可重用标识符
private let WJComposePictureViewCellId = "SHComposePictureViewCellId"
class WJComposePictureView: UICollectionView {
    // 定义一个闭包通知vc弹出相册
    var closure:(()->())?
    
    var imageList: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addImages(image:UIImage) {
        
        imageList.append(image)
        hidden = false
        reloadData()
    }
    
    // MARK: -  设置视图
    private func setupUI(){
         hidden = true
        backgroundColor = RandomColor()
        let cellMargin: CGFloat = 5
        let cellWH = (SCREENW - 20 - cellMargin*2)/3
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        // 设置item
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        // 设置数据源
        dataSource  = self
        delegate = self
        registerClass(WJComposePictureViewCell.self, forCellWithReuseIdentifier: WJComposePictureViewCellId)
    }
}

extension WJComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     
        let listCount = imageList.count
        
        if listCount == 0 || listCount == 9 {
            return listCount
        }
            return imageList.count + 1
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WJComposePictureViewCellId, forIndexPath: indexPath) as! WJComposePictureViewCell
         // 判断是最后一个item 代表要显示加号图片
        if imageList.count == indexPath.item {

            cell.image = nil
        }else {
            cell.image = imageList[indexPath.item]
        }
   
        cell.closure = {[weak self] in
            self?.imageList .removeAtIndex(indexPath.item)
            
            if self?.imageList.count == 0 {
                
                self?.hidden = true
            }
            self?.reloadData()
        }
   
        return cell
    }

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    collectionView.deselectItemAtIndexPath(indexPath, animated: true)
    
    // 代表点击的为加号按钮
    if indexPath.item == imageList.count{
        closure?()
    }
    
    }

}


//自定义cell
class WJComposePictureViewCell: UICollectionViewCell {
    //定义一个闭包
    var closure: (()->())?
    
    var image: UIImage?
    {
        
        didSet{
            
            if image == nil {
                
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                closeButton.hidden = true
                
            }else {
                
                bgImageView.image = image
                
                //解决cell复用方法一
//               bgImageView.highlightedImage = nil
//                closeButton.hidden = false
                
            }
          
        }
    }
    ////解决cell复用方法二
    override func prepareForReuse() {
        super.prepareForReuse()
        
         bgImageView.highlightedImage = nil
        closeButton.hidden = false
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
  
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(closeButton)
        //添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        
        closeButton.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
    }
    
    func closeBtn() {
        
        closure?()
        
    }
    
    //懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    
    private lazy var closeButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "closeBtn", forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
}
